{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n",
      "/usr/lib/python3/dist-packages/requests/__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.3) or chardet (3.0.4) doesn't match a supported version!\n",
      "  RequestsDependencyWarning)\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "with open('train-test.json') as fopen:\n",
    "    dataset = json.load(fopen)\n",
    "    \n",
    "with open('dictionary.json') as fopen:\n",
    "    dictionary = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = dataset['train_X']\n",
    "train_Y = dataset['train_Y']\n",
    "test_X = dataset['test_X']\n",
    "test_Y = dataset['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['from', 'to'])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dictionary.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "dictionary_from = dictionary['from']['dictionary']\n",
    "rev_dictionary_from = dictionary['from']['rev_dictionary']\n",
    "\n",
    "dictionary_to = dictionary['to']['dictionary']\n",
    "rev_dictionary_to = dictionary['to']['rev_dictionary']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "GO = dictionary_from['GO']\n",
    "PAD = dictionary_from['PAD']\n",
    "EOS = dictionary_from['EOS']\n",
    "UNK = dictionary_from['UNK']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Rachel Pike : The science behind a climate headline EOS'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "for i in range(len(train_X)):\n",
    "    train_X[i] += ' EOS'\n",
    "    \n",
    "train_X[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'How can I speak in <NUM> minutes about the bonds of women over three generations , about how the astonishing strength of those bonds took hold in the life of a four - year - old girl huddled with her young sister , her mother and her grandmother for five days and nights in a small boat in the China Sea more than <NUM> years ago , bonds that took hold in the life of that small girl and never let go - - that small girl now living in San Francisco and speaking to you today ? EOS'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "for i in range(len(test_X)):\n",
    "    test_X[i] += ' EOS'\n",
    "    \n",
    "test_X[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "def layer_normalization(inputs, block_name, reuse, epsilon=1e-8):\n",
    "    with tf.variable_scope(block_name, reuse = reuse):\n",
    "        mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True)\n",
    "        normalized = (inputs - mean) / (tf.sqrt(variance + epsilon))\n",
    "\n",
    "        params_shape = inputs.get_shape()[-1:]\n",
    "        gamma = tf.get_variable('gamma', params_shape, tf.float32, tf.ones_initializer())\n",
    "        beta = tf.get_variable('beta', params_shape, tf.float32, tf.zeros_initializer())\n",
    "\n",
    "        outputs = gamma * normalized + beta\n",
    "        return outputs\n",
    "\n",
    "def conv1d(input_, output_channels, block_name, reuse, dilation = 1, filter_width = 1, causal = False):\n",
    "    with tf.variable_scope(block_name, reuse = reuse):\n",
    "        w = tf.get_variable('w',  [1, filter_width, int(input_.get_shape()[-1]), output_channels],\n",
    "                            tf.float32, tf.initializers.random_normal(stddev = 0.02))\n",
    "        b = tf.get_variable('b',  [output_channels],\n",
    "                            tf.float32, tf.zeros_initializer())\n",
    "        if causal:\n",
    "            padding = [[0, 0], [(filter_width - 1) * dilation, 0], [0, 0]]\n",
    "            padded = tf.pad(input_, padding)\n",
    "            input_expanded = tf.expand_dims(padded, dim = 1)\n",
    "            out = tf.nn.atrous_conv2d(input_expanded, w, rate = dilation, padding = 'VALID') + b\n",
    "        else:\n",
    "            input_expanded = tf.expand_dims(input_, dim = 1)\n",
    "            out = tf.nn.atrous_conv2d(input_expanded, w, rate = dilation, padding = 'SAME') + b\n",
    "        return tf.squeeze(out, [1])\n",
    "\n",
    "def bytenet_residual_block(input_, dilation, layer_no, \n",
    "                            residual_channels, filter_width, block_type,\n",
    "                            causal = True, reuse = False):\n",
    "    block_name = \"bytenet_{}_layer_{}_{}\".format(block_type, layer_no, dilation)\n",
    "    print(block_name)\n",
    "    with tf.variable_scope(block_name, reuse = reuse):\n",
    "        relu1 = tf.nn.relu(layer_normalization(input_, block_name + '_0', reuse))\n",
    "        conv1 = conv1d(relu1, residual_channels, block_name + '_0', reuse)\n",
    "        relu2 = tf.nn.relu(layer_normalization(conv1, block_name + '_1', reuse))\n",
    "        dilated_conv = conv1d(relu2, residual_channels,\n",
    "                              block_name + '_1', reuse,\n",
    "                              dilation, filter_width,\n",
    "                              causal = causal)\n",
    "        print(dilated_conv)\n",
    "        relu3 = tf.nn.relu(layer_normalization(dilated_conv, block_name + '_2', reuse))\n",
    "        conv2 = conv1d(relu3, 2 * residual_channels, block_name + '_2', reuse)\n",
    "        return input_ + conv2\n",
    "    \n",
    "class ByteNet:\n",
    "    def __init__(self, from_vocab_size, to_vocab_size, channels, encoder_dilations,\n",
    "                decoder_dilations, encoder_filter_width, decoder_filter_width,\n",
    "                learning_rate = 1e-3, beta1=0.5):\n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        target_1 = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        embedding_channels = 2 * channels\n",
    "        max_seq = tf.maximum(tf.reduce_max(self.Y_seq_len), tf.reduce_max(self.X_seq_len))\n",
    "        w_source_embedding = tf.Variable(tf.random_normal([from_vocab_size, \n",
    "                                                           embedding_channels], stddev = 0.02))\n",
    "        w_target_embedding = tf.Variable(tf.random_normal([to_vocab_size, \n",
    "                                                           embedding_channels], stddev = 0.02))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            source_embedding = tf.nn.embedding_lookup(w_source_embedding, x)\n",
    "            target_1_embedding = tf.nn.embedding_lookup(w_target_embedding, y)\n",
    "        \n",
    "        \n",
    "            curr_input = source_embedding\n",
    "            for layer_no, dilation in enumerate(encoder_dilations):\n",
    "                curr_input = bytenet_residual_block(curr_input, dilation, \n",
    "                                                    layer_no, channels, \n",
    "                                                    encoder_filter_width,\n",
    "                                                    'encoder',\n",
    "                                                    causal = False, reuse = reuse)\n",
    "            encoder_output = curr_input\n",
    "            combined_embedding = target_1_embedding + encoder_output\n",
    "            curr_input = combined_embedding\n",
    "            for layer_no, dilation in enumerate(decoder_dilations):\n",
    "                curr_input = bytenet_residual_block(curr_input, dilation, \n",
    "                                                    layer_no, channels, \n",
    "                                                    encoder_filter_width, \n",
    "                                                    'decoder',\n",
    "                                                    causal = False, reuse = reuse)\n",
    "            with tf.variable_scope('logits', reuse = reuse):\n",
    "                return conv1d(curr_input, to_vocab_size, 'logits', reuse)\n",
    "        \n",
    "        self.logits = forward(self.X, target_1)\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, max_seq, dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        def cond(i, y, temp):\n",
    "            return i < tf.reduce_max(max_seq)\n",
    "        \n",
    "        def body(i, y, temp):\n",
    "            logits = forward(self.X, y, reuse = True)\n",
    "            ids = tf.argmax(logits, -1)[:, i]\n",
    "            ids = tf.expand_dims(ids, -1)\n",
    "            temp = tf.concat([temp[:, 1:], ids], -1)\n",
    "            y = tf.concat([temp[:, -(i+1):], temp[:, :-(i+1)]], -1)\n",
    "            y = tf.reshape(y, [tf.shape(temp)[0], max_seq])\n",
    "            i += 1\n",
    "            return i, y, temp\n",
    "        \n",
    "        target = tf.fill([batch_size, max_seq], GO)\n",
    "        target = tf.cast(target, tf.int64)\n",
    "        self.target = target\n",
    "        \n",
    "        _, self.predicting_ids, _ = tf.while_loop(cond, body, \n",
    "                                                  [tf.constant(0), target, target])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "residual_channels = 128\n",
    "encoder_dilations = [1,2,4,8,16,1,2,4,8,16]\n",
    "decoder_dilations = [1,2,4,8,16,1,2,4,8,16]\n",
    "encoder_filter_width = 3\n",
    "decoder_filter_width = 3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "bytenet_encoder_layer_0_1\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/dispatch.py:180: calling expand_dims (from tensorflow.python.ops.array_ops) with dim is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use the `axis` argument instead\n",
      "Tensor(\"bytenet_encoder_layer_0_1/bytenet_encoder_layer_0_1_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_1_2\n",
      "Tensor(\"bytenet_encoder_layer_1_2/bytenet_encoder_layer_1_2_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_2_4\n",
      "Tensor(\"bytenet_encoder_layer_2_4/bytenet_encoder_layer_2_4_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_3_8\n",
      "Tensor(\"bytenet_encoder_layer_3_8/bytenet_encoder_layer_3_8_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_4_16\n",
      "Tensor(\"bytenet_encoder_layer_4_16/bytenet_encoder_layer_4_16_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_5_1\n",
      "Tensor(\"bytenet_encoder_layer_5_1/bytenet_encoder_layer_5_1_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_6_2\n",
      "Tensor(\"bytenet_encoder_layer_6_2/bytenet_encoder_layer_6_2_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_7_4\n",
      "Tensor(\"bytenet_encoder_layer_7_4/bytenet_encoder_layer_7_4_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_8_8\n",
      "Tensor(\"bytenet_encoder_layer_8_8/bytenet_encoder_layer_8_8_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_9_16\n",
      "Tensor(\"bytenet_encoder_layer_9_16/bytenet_encoder_layer_9_16_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_0_1\n",
      "Tensor(\"bytenet_decoder_layer_0_1/bytenet_decoder_layer_0_1_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_1_2\n",
      "Tensor(\"bytenet_decoder_layer_1_2/bytenet_decoder_layer_1_2_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_2_4\n",
      "Tensor(\"bytenet_decoder_layer_2_4/bytenet_decoder_layer_2_4_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_3_8\n",
      "Tensor(\"bytenet_decoder_layer_3_8/bytenet_decoder_layer_3_8_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_4_16\n",
      "Tensor(\"bytenet_decoder_layer_4_16/bytenet_decoder_layer_4_16_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_5_1\n",
      "Tensor(\"bytenet_decoder_layer_5_1/bytenet_decoder_layer_5_1_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_6_2\n",
      "Tensor(\"bytenet_decoder_layer_6_2/bytenet_decoder_layer_6_2_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_7_4\n",
      "Tensor(\"bytenet_decoder_layer_7_4/bytenet_decoder_layer_7_4_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_8_8\n",
      "Tensor(\"bytenet_decoder_layer_8_8/bytenet_decoder_layer_8_8_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_9_16\n",
      "Tensor(\"bytenet_decoder_layer_9_16/bytenet_decoder_layer_9_16_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py:1354: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "bytenet_encoder_layer_0_1\n",
      "Tensor(\"while/bytenet_encoder_layer_0_1/bytenet_encoder_layer_0_1_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_1_2\n",
      "Tensor(\"while/bytenet_encoder_layer_1_2/bytenet_encoder_layer_1_2_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_2_4\n",
      "Tensor(\"while/bytenet_encoder_layer_2_4/bytenet_encoder_layer_2_4_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_3_8\n",
      "Tensor(\"while/bytenet_encoder_layer_3_8/bytenet_encoder_layer_3_8_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_4_16\n",
      "Tensor(\"while/bytenet_encoder_layer_4_16/bytenet_encoder_layer_4_16_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_5_1\n",
      "Tensor(\"while/bytenet_encoder_layer_5_1/bytenet_encoder_layer_5_1_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_6_2\n",
      "Tensor(\"while/bytenet_encoder_layer_6_2/bytenet_encoder_layer_6_2_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_7_4\n",
      "Tensor(\"while/bytenet_encoder_layer_7_4/bytenet_encoder_layer_7_4_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_8_8\n",
      "Tensor(\"while/bytenet_encoder_layer_8_8/bytenet_encoder_layer_8_8_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_encoder_layer_9_16\n",
      "Tensor(\"while/bytenet_encoder_layer_9_16/bytenet_encoder_layer_9_16_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_0_1\n",
      "Tensor(\"while/bytenet_decoder_layer_0_1/bytenet_decoder_layer_0_1_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_1_2\n",
      "Tensor(\"while/bytenet_decoder_layer_1_2/bytenet_decoder_layer_1_2_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_2_4\n",
      "Tensor(\"while/bytenet_decoder_layer_2_4/bytenet_decoder_layer_2_4_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_3_8\n",
      "Tensor(\"while/bytenet_decoder_layer_3_8/bytenet_decoder_layer_3_8_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_4_16\n",
      "Tensor(\"while/bytenet_decoder_layer_4_16/bytenet_decoder_layer_4_16_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_5_1\n",
      "Tensor(\"while/bytenet_decoder_layer_5_1/bytenet_decoder_layer_5_1_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_6_2\n",
      "Tensor(\"while/bytenet_decoder_layer_6_2/bytenet_decoder_layer_6_2_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_7_4\n",
      "Tensor(\"while/bytenet_decoder_layer_7_4/bytenet_decoder_layer_7_4_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_8_8\n",
      "Tensor(\"while/bytenet_decoder_layer_8_8/bytenet_decoder_layer_8_8_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n",
      "bytenet_decoder_layer_9_16\n",
      "Tensor(\"while/bytenet_decoder_layer_9_16/bytenet_decoder_layer_9_16_1_1/Squeeze:0\", shape=(?, ?, 128), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = ByteNet(len(dictionary_from), len(dictionary_to), \n",
    "                residual_channels, encoder_dilations, decoder_dilations,\n",
    "                encoder_filter_width,decoder_filter_width)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "def str_idx(corpus, dic):\n",
    "    X = []\n",
    "    for i in corpus:\n",
    "        ints = []\n",
    "        for k in i.split():\n",
    "            ints.append(dic.get(k,UNK))\n",
    "        X.append(ints)\n",
    "    return X\n",
    "\n",
    "def pad_sentence_batch(sentence_batch, sentence_batch_y, pad_int):\n",
    "    x, y = [], []\n",
    "    max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n",
    "    max_sentence_len_y = max([len(sentence) for sentence in sentence_batch_y])\n",
    "    max_sentence_len = max(max_sentence_len, max_sentence_len_y)\n",
    "    for no, sentence in enumerate(sentence_batch):\n",
    "        x.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n",
    "        y.append(sentence_batch_y[no] + [pad_int] * (max_sentence_len - len(sentence_batch_y[no])))\n",
    "    return x, y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = str_idx(train_X, dictionary_from)\n",
    "test_X = str_idx(test_X, dictionary_from)\n",
    "train_Y = str_idx(train_Y, dictionary_to)\n",
    "test_Y = str_idx(test_Y, dictionary_to)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:58<00:00,  2.91it/s, accuracy=0.908, cost=0.589]\n",
      "minibatch loop: 100%|██████████| 23/23 [00:02<00:00, 10.36it/s, accuracy=0.944, cost=0.387]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 2.536019, training avg acc 0.598162\n",
      "epoch 1, testing avg loss 0.370165, testing avg acc 0.942144\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:30<00:00,  3.15it/s, accuracy=0.959, cost=0.218] \n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.21it/s, accuracy=0.983, cost=0.147]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 0.236962, training avg acc 0.962103\n",
      "epoch 2, testing avg loss 0.197636, testing avg acc 0.972153\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:30<00:00,  3.15it/s, accuracy=0.983, cost=0.0849]\n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.35it/s, accuracy=0.989, cost=0.123]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 0.127662, training avg acc 0.976652\n",
      "epoch 3, testing avg loss 0.179455, testing avg acc 0.977238\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:30<00:00,  3.15it/s, accuracy=0.951, cost=0.311]\n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.28it/s, accuracy=0.972, cost=0.238]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 0.304175, training avg acc 0.954207\n",
      "epoch 4, testing avg loss 0.269206, testing avg acc 0.962994\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:32<00:00,  3.14it/s, accuracy=0.984, cost=0.0569]\n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.25it/s, accuracy=0.994, cost=0.102] \n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 0.090168, training avg acc 0.981978\n",
      "epoch 5, testing avg loss 0.164325, testing avg acc 0.983717\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:34<00:00,  3.11it/s, accuracy=0.992, cost=0.026] \n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.06it/s, accuracy=0.989, cost=0.138]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 0.044207, training avg acc 0.989879\n",
      "epoch 6, testing avg loss 0.196745, testing avg acc 0.983652\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:35<00:00,  3.11it/s, accuracy=0.997, cost=0.0106] \n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.17it/s, accuracy=0.983, cost=0.165]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 0.029949, training avg acc 0.992504\n",
      "epoch 7, testing avg loss 0.207383, testing avg acc 0.982795\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:35<00:00,  3.11it/s, accuracy=0.997, cost=0.00837]\n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.11it/s, accuracy=0.977, cost=0.181]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 0.020005, training avg acc 0.994840\n",
      "epoch 8, testing avg loss 0.196328, testing avg acc 0.983033\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:35<00:00,  3.11it/s, accuracy=0.999, cost=0.0154] \n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.12it/s, accuracy=0.989, cost=0.137]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 0.013636, training avg acc 0.996435\n",
      "epoch 9, testing avg loss 0.183184, testing avg acc 0.985359\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:35<00:00,  3.10it/s, accuracy=0.999, cost=0.00684]\n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.17it/s, accuracy=0.994, cost=0.138]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 0.012246, training avg acc 0.996850\n",
      "epoch 10, testing avg loss 0.198246, testing avg acc 0.985733\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:35<00:00,  3.11it/s, accuracy=0.995, cost=0.0152] \n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.19it/s, accuracy=0.989, cost=0.142]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 0.011877, training avg acc 0.996858\n",
      "epoch 11, testing avg loss 0.203655, testing avg acc 0.983977\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:35<00:00,  3.11it/s, accuracy=1, cost=0.00271]    \n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.20it/s, accuracy=0.994, cost=0.138]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 0.008184, training avg acc 0.997783\n",
      "epoch 12, testing avg loss 0.208487, testing avg acc 0.986197\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:37<00:00,  3.09it/s, accuracy=0.997, cost=0.00881]\n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.14it/s, accuracy=0.994, cost=0.156]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 0.021827, training avg acc 0.994676\n",
      "epoch 13, testing avg loss 0.212016, testing avg acc 0.987836\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:38<00:00,  3.08it/s, accuracy=1, cost=0.00131]    \n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.17it/s, accuracy=0.994, cost=0.164]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 0.004379, training avg acc 0.998775\n",
      "epoch 14, testing avg loss 0.221635, testing avg acc 0.987110\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:38<00:00,  3.08it/s, accuracy=1, cost=0.000921]   \n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.08it/s, accuracy=0.994, cost=0.153]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 0.005973, training avg acc 0.998396\n",
      "epoch 15, testing avg loss 0.219805, testing avg acc 0.986864\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:42<00:00,  3.04it/s, accuracy=0.997, cost=0.00717]\n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.09it/s, accuracy=0.994, cost=0.177]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 0.005192, training avg acc 0.998582\n",
      "epoch 16, testing avg loss 0.230734, testing avg acc 0.985904\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:38<00:00,  3.08it/s, accuracy=1, cost=0.00225]    \n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.08it/s, accuracy=0.994, cost=0.147]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 0.005340, training avg acc 0.998546\n",
      "epoch 17, testing avg loss 0.223914, testing avg acc 0.985517\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:43<00:00,  3.04it/s, accuracy=1, cost=0.000872]   \n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.14it/s, accuracy=0.994, cost=0.157]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 0.016996, training avg acc 0.996231\n",
      "epoch 18, testing avg loss 0.212258, testing avg acc 0.988296\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:38<00:00,  3.08it/s, accuracy=1, cost=0.000745]   \n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.20it/s, accuracy=0.994, cost=0.166]\n",
      "minibatch loop:   0%|          | 0/1042 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 0.002376, training avg acc 0.999325\n",
      "epoch 19, testing avg loss 0.227242, testing avg acc 0.988243\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1042/1042 [05:38<00:00,  3.08it/s, accuracy=1, cost=0.000225]   \n",
      "minibatch loop: 100%|██████████| 23/23 [00:01<00:00, 13.02it/s, accuracy=0.994, cost=0.163]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 0.002386, training avg acc 0.999336\n",
      "epoch 20, testing avg loss 0.224342, testing avg acc 0.987937\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x, batch_y = pad_sentence_batch(train_X[i : index], train_Y[i : index], PAD)\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x, batch_y = pad_sentence_batch(test_X[i : index], test_Y[i : index], PAD)\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "rev_dictionary_to = {int(k): v for k, v in rev_dictionary_to.items()}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(20, 123)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test_size = 20\n",
    "\n",
    "batch_x, batch_y = pad_sentence_batch(test_X[: test_size], test_Y[: test_size], PAD)\n",
    "feed = {model.X: batch_x, model.Y: batch_y}\n",
    "logits = sess.run(model.predicting_ids, feed_dict = feed)\n",
    "logits.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 predict: oh The The The War The War The War The War The The War The War The War oh War The War and and Box The War The The War The War The War The Edward The War The War The War The oh War The War The War The War Luther War The War The War War oh oh War War The The War The War oh The War The War The War The War The War The oh Box The War The War The The War The Edward The War The War The War Edward War War The War The War War War The War The War The War The War The War oh War oh War oh War The Đất\n",
      "0 actual: Làm sao tôi có thể trình bày trong <NUM> phút về sợi dây liên kết những người phụ nữ qua ba thế hệ , về việc làm thế nào những sợi dây mạnh mẽ đáng kinh ngạc ấy đã níu chặt lấy cuộc sống của một cô bé bốn tuổi co quắp với đứa em gái nhỏ của cô bé , với mẹ và bà trong suốt năm ngày đêm trên con thuyền nhỏ lênh đênh trên Biển Đông hơn <NUM> năm trước , những sợi dây liên kết đã níu lấy cuộc đời cô bé ấy và không bao giờ rời đi - - cô bé ấy giờ sống ở San Francisco và đang nói chuyện với các bạn hôm nay ?\n",
      "\n",
      "1 predict: Kiran The War The War The War War War War The War The War War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War oh War Đất\n",
      "1 actual: Câu chuyện này chưa kết thúc .\n",
      "\n",
      "2 predict: Kiran The Yo The War The War The War War War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War oh War Đất\n",
      "2 actual: Nó là một trò chơi ghép hình vẫn đang được xếp .\n",
      "\n",
      "3 predict: Edward Edward The The War The War The War The War War War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War oh War Đất\n",
      "3 actual: Hãy để tôi kể cho các bạn về vài mảnh ghép nhé .\n",
      "\n",
      "4 predict: oh Emdin The The War The War The War The War The War War War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War oh War Đất\n",
      "4 actual: Hãy tưởng tượng mảnh đầu tiên : một người đàn ông đốt cháy sự nghiệp cả đời mình .\n",
      "\n",
      "5 predict: Julia The The The War The War War The The War War The War The War The Like Yo The War and War The War The Edward War The War The War The War War The War The War The War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War oh War Đất\n",
      "5 actual: Ông là nhà thơ , nhà viết kịch , một người mà cả cuộc đời chênh vênh trên tia hi vọng duy nhất rằng đất nước ông sẽ độc lập tự do .\n",
      "\n",
      "6 predict: Julia The War The War The War War The War The War The War War War Edward oh War The War The War War War War The War The War War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War oh War Đất\n",
      "6 actual: Hãy tưởng tượng ông , một người cộng sản tiến vào , đối diện sự thật rằng cả cuộc đời ông đã phí hoài .\n",
      "\n",
      "7 predict: oh The War The War The War The oh War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War oh War Đất\n",
      "7 actual: Ngôn từ , qua bao năm tháng là bạn đồng hành với ông , giờ quay ra chế giễu ông .\n",
      "\n",
      "8 predict: Julia The Box The War War War War The War The War War War War War The War War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War oh War Đất\n",
      "8 actual: Ông rút lui vào yên lặng .\n",
      "\n",
      "9 predict: Sam Edward The The War War War War War War The War War War War War War The War War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War The Đất\n",
      "9 actual: Ông qua đời , bị lịch sử quật ngã .\n",
      "\n",
      "10 predict: Julia The The War War War War War The War War War War War War The War War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War The Đất\n",
      "10 actual: Ông là ông của tôi .\n",
      "\n",
      "11 predict: Edward The War The War The War The War War War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War oh War Đất\n",
      "11 actual: Tôi chưa bao giờ gặp ông ngoài đời .\n",
      "\n",
      "12 predict: oh The War The War War The War The War The War War War War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War oh War Đất\n",
      "12 actual: Nhưng cuộc đời ta nhiều hơn những gì ta lưu trong kí ức nhiều .\n",
      "\n",
      "13 predict: Julia The oh The The War The War The War The War War War War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War oh War Đất\n",
      "13 actual: Bà tôi chưa bao giờ cho phép tôi quên cuộc đời của ông .\n",
      "\n",
      "14 predict: Julia The War The War The War The War The Edward War The War The War War War oh Box oh War The War War and War The War The War The War The War The War The War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War oh War Đất\n",
      "14 actual: Nhiệm vụ của tôi là không để cuộc đời ấy qua trong vô vọng , và bài học của tôi là nhận ra rằng , vâng , lịch sử đã cố quật ngã chúng tôi , nhưng chúng tôi đã chịu đựng được .\n",
      "\n",
      "15 predict: oh The The The War War The War The War The War Edward War Sweeney War War Yo oh War War War The War War War War The War The War War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War The Đất\n",
      "15 actual: Mảnh ghép tiếp theo của tấm hình là một con thuyền trong sớm hoàng hôn lặng lẽ trườn ra biển .\n",
      "\n",
      "16 predict: oh The Edward The War The The War The War The War The War Like War Yo War The War The War oh War The War The War The War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War The Đất\n",
      "16 actual: Mẹ tôi , Mai , mới <NUM> tuổi khi ba của mẹ mất - - đã lập gia đình , một cuộc hôn nhân sắp đặt trước , đã có hai cô con gái nhỏ .\n",
      "\n",
      "17 predict: oh The The The War War The War War The War oh War The War The War The War The The War The War The War The War The War The War The War The War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War The Đất\n",
      "17 actual: Với mẹ , cuộc đời cô đọng vào nhiệm vụ duy nhất : để gia đình mẹ trốn thoát và bắt đầu cuộc sống mới ở Úc .\n",
      "\n",
      "18 predict: Kiran Edward War The War The War War The War The War The War War War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War The Đất\n",
      "18 actual: Mẹ không bao giờ chấp nhận được là mẹ sẽ không thành công .\n",
      "\n",
      "19 predict: Edward The The The The War The War The War The War The War War War The War The Like The War The War War The War The War The War The War The War War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War The War oh War oh War oh War oh War Đất\n",
      "19 actual: Thế là sau bốn năm , một trường thiên đằng đẵng hơn cả trong truyện , một chiếc thuyền trườn ra biển nguỵ trang là thuyền đánh cá .\n",
      "\n"
     ]
    }
   ],
   "source": [
    "rejected = ['PAD', 'EOS', 'UNK', 'GO']\n",
    "\n",
    "for i in range(test_size):\n",
    "    predict = [rev_dictionary_to[i] for i in logits[i] if rev_dictionary_to[i] not in rejected]\n",
    "    actual = [rev_dictionary_to[i] for i in batch_y[i] if rev_dictionary_to[i] not in rejected]\n",
    "    print(i, 'predict:', ' '.join(predict))\n",
    "    print(i, 'actual:', ' '.join(actual))\n",
    "    print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
